<?php

namespace app;

use app\exception\ApiException;
use app\exception\AuthException;
use app\exception\ValidateException;
use app\utils\Json;
use support\Container;
use support\exception\BusinessException;
use support\Log;
use think\db\exception\DbException;
use Webman\Http\Response;
use Throwable;
use support\exception\Handler;
use Webman\Http\Request;

class ExceptionHandler extends Handler
{
    public $dontReport = [
        BusinessException::class,
        ValidateException::class,
    ];

    public function report(Throwable $exception): void
    {
        parent::report($exception);
    }

    public function render(Request $request, Throwable $e): Response
    {
        $message = config('app.debug', false) ? [
            'file'     => $e->getFile(),
            'line'     => $e->getLine(),
            'trace'    => (string)$e,
            'previous' => $e->getPrevious() ?? '',
        ] : [];

        if ($e instanceof DbException) {
            return fail('数据获取异常', $message);
        } elseif (
            $e instanceof ApiException ||
            $e instanceof ValidateException ||
            $e instanceof AuthException ||
            $e instanceof BusinessException
        ) {
            return Container::get(Json::class)->make($e->getCode() ?: 400, $e->getMessage(), $message);
        } else {
            return Container::get(Json::class)->code(500)->make(400, $e->getMessage(), $message);
        }
    }
}
